﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using Husb.Security;

using CentralOffice.Admin.Data;
using CentralOffice.Admin.BusinessActions;
using DepartmentTable = CentralOffice.Admin.Data.Departments.DepartmentsDataTable;
using DepartmentRow = CentralOffice.Admin.Data.Departments.DepartmentsRow;
using Husb.Util;
using Microsoft.Practices.EnterpriseLibrary.Security.Database;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Security;
using Microsoft.Practices.EnterpriseLibrary.Security.Configuration;


namespace CentralOffice.WebClient
{
    public partial class Initialize : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                GenericMembershipProvider membershipProvider = Membership.Provider as GenericMembershipProvider;
                if (membershipProvider == null)
                {
                    throw new Exception("MembershipProvider没有配置！");
                }

                GenericRoleProvider roleProvider = Roles.Provider as GenericRoleProvider;
                if (roleProvider == null)
                {
                    throw new Exception("RoleProvider没有配置！");
                }

                DepartmentRow d = Department.GetRootDepartment();
                if (d != null)
                {
                    txtDepartment.Text = d.Name;
                }

                DbRuleManager dbRuleManager = SiteUtil.GetRuleManager();
                DbAuthorizationRuleData rule = dbRuleManager.GetRule(AuthorizationRules.IsSystemAdministrator);
                if (rule != null)
                {
                    string roles = rule.Expression.Replace(" OR ", ",").Replace("R:", "");
                    string[] rs = roles.Trim().Split(',');
                    if (rs.Length > 0 && rs[0].Length > 0)
                    {
                        List<RoleInfo> roleList = roleProvider.GetAllRoleList();
                        string roleName = Husb.Util.CommonUtil.InputText(txtRole.Text);
                        RoleInfo role = roleList.Find(r => r.RoleName == rs[0]);

                        if (role != null)
                        {
                            txtRole.Text = role.RoleName;
                        }
                    }
                }

                if (txtRole.Text.Length > 0)
                {
                    string[] admin = roleProvider.GetUsersInRole(txtRole.Text);

                    if (admin.Length > 0)
                    {
                        txtUsername.Text = CommonUtil.StringArray2String(admin, false);
                    }
                }

                if (txtDepartment.Text.Length > 0
                   && txtRole.Text.Length > 0
                   && txtUsername.Text.Length > 0)
                {
                    lblFinish.Visible = true;
                }
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            GenericMembershipProvider membershipProvider = Membership.Provider as GenericMembershipProvider;
            if (membershipProvider == null)
            {
                throw new Exception("MembershipProvider没有配置！");
            }

            GenericRoleProvider roleProvider = Roles.Provider as GenericRoleProvider;
            if (roleProvider == null)
            {
                throw new Exception("RoleProvider没有配置！");
            }
            // 添加顶级部门
            DepartmentRow d = Department.GetRootDepartment();
            if (d == null)
            {
                Departments ds = new Departments();
                d = ds._Departments.NewDepartmentsRow();
                Guid departmentId = Guid.NewGuid();
                SiteUtil.PopulateCommonField(d, departmentId);
                d.Name = CommonUtil.InputText(txtDepartment.Text);
                ds._Departments.AddDepartmentsRow(d);

                Department.Update(ds);
            }

            // 添加管理员角色
            RoleInfo role = null;
            string roleName = Husb.Util.CommonUtil.InputText(txtRole.Text);
            DbRuleManager dbRuleManager = SiteUtil.GetRuleManager();
            DbAuthorizationRuleData rule = dbRuleManager.GetRule(AuthorizationRules.IsSystemAdministrator);
            if (rule != null)
            {
                string roles = rule.Expression.Replace(" OR ", ",").Replace("R:", "");
                string[] rs = roles.Trim().Split(',');
                if (rs.Length > 0 && rs[0].Length > 0)
                {
                    List<RoleInfo> roleList = roleProvider.GetAllRoleList();
                    
                    foreach (string tmp in rs)
                    {
                        if (role == null)
                        {
                            role = roleList.Find(r => r.RoleName == tmp);
                        }
                        if (role != null)
                        {
                            break;
                        }
                    }
                    if (role == null)
                    {
                        role = new RoleInfo(Guid.NewGuid(), roleName, roleName);
                        roleProvider.CreateRole(roleName, -1);
                    }
                }
            }

            // 添加管理员帐号
            string username = CommonUtil.InputText(txtUsername.Text);
            string[] admin = roleProvider.GetUsersInRole(txtRole.Text);
            if (!admin.Contains<string>(username))
            {
                MembershipUserEx user = Membership.GetUser(username, false) as MembershipUserEx;
                if (user == null)
                {
                    user = Membership.GetUser(username, true) as MembershipUserEx;
                }

                if (user == null)
                {
                    MembershipCreateStatus status;
                    MembershipUserEx u = membershipProvider.CreateUser(username,
                        null,        // empid
                        //d.Id,      // ownerid
                        0,           // userType
                        username,    // password
                        "admin@email.com",
                        "PasswordQuestion",
                        "PasswordAnswer",
                        true,           // IsApprove
                        Guid.NewGuid(), //UserId
                        out status);

                    //将管理员添加到管理员角色
                    roleProvider.AddUsersToRoles(new string[] { username }, new string[] { roleName });
                    //roleProvider.AddUsersToRoles(new string[] { username }, new string[] { role.RoleName });
                }
            }

            // 添加操作权限：是系统管理员
            if (rule == null)
            {
                dbRuleManager.Insert(Guid.NewGuid(), AuthorizationRules.IsSystemAdministrator, "R:" + role.RoleName, 0, AuthorizationRules.IsSystemAdministrator);
            }

            //if (admin != null)
            //{
            //    membershipProvider.DeleteUser(username, true);
            //}

            //MembershipCreateStatus status;
            //MembershipUserEx u = membershipProvider.CreateUser(username,
            //    null, // empid
            //    //d.Id, // ownerid
            //    username,
            //    "admin@email.com",
            //    "PasswordQuestion",
            //    "PasswordAnswer",
            //    true, // IsApprove
            //    Guid.NewGuid(), //UserId
            //    out status);
            //Roles.AddUserToRole(UserEditLayout1.UserName, 

            //将管理员添加到管理员角色
            //roleProvider.AddUsersToRoles(new string[] { username }, new string[] { role.RoleName });

            // 添加操作权限：是系统管理员
            //DbRuleManager dbRuleManager = SiteUtil.GetRuleManager();

            

            //if (d == null || r == null)
            //{
            //    WebUtils.ShowMessage(litError, "超时，请重新填写！");
            //    SetPanel(0);
            //    return;
            //}

            //// 添加根部门
            //if (Department.GetRoot() == null)
            //{
            //    Department.Create(d, true);
            //}
            //else
            //{
            //    d = Department.GetRoot();
            //    WebUtils.ShowMessage(litFinished, "根部门" + d.Name + "已经存在！");
            //}

            //// 添加系统管理员角色
            //if (!roleProvider.RoleExists(r.RoleName, d.Id))
            //{
            //    roleProvider.CreateRole(r.RoleName, d.Id);
            //}
            //else
            //{
            //    roleProvider.DeleteRole(r.RoleName, false, d.Id);
            //    roleProvider.CreateRole(r.RoleName, d.Id);
            //}

            //// 创建管理员用户
            //if (Membership.GetUser(UserEditLayout1.UserName, false) != null || Membership.GetUser(UserEditLayout1.UserName, true) != null)
            //{
            //    membershipProvider.DeleteUser(UserEditLayout1.UserName, true);
            //}
            //MembershipCreateStatus status;
            //MembershipUserInfo u = membershipProvider.CreateUser(UserEditLayout1.UserName,
            //    null, // empid
            //    d.Id, // ownerid
            //    UserEditLayout1.Password,
            //    UserEditLayout1.Email,
            //    "PasswordQuestion",
            //    "PasswordAnswer",
            //    true, // IsApprove
            //    Guid.NewGuid(), //UserId
            //    out status);
            ////Roles.AddUserToRole(UserEditLayout1.UserName, 

            ////将管理员添加到管理员角色
            //roleProvider.AddUsersToRoles(new string[] { username }, new string[] { role.RoleName });


            //// 添加操作权限：是系统管理员
            //AuthorizationProviderDbRuleProvider dbProvider = new AuthorizationProviderDbRuleProvider(null);
            //dbProvider.InsertRule(Guid.NewGuid(), SystemOperation.IsSystemAdministrator, SystemOperation.IsSystemAdministrator, 0, "R:" + r.RoleName, null);

            Server.Transfer("default1.htm");
        }
    }
}
